<template>
  <div class="app-container">
	<div class="app-layout">
		<div class="pane" style="width: 100%;">
			<div class="head">
				<span>MQTT数据列表</span>
			</div>
			<div class="body">
				<div class="table-tool-bar">
					<div>
						<el-button type="primary" icon="plus" @click="editMqttDrawerRef.openDialog(null,'add')">新增</el-button>
						<el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
						  删除
						</el-button>
					</div>
					<div>
						<el-input
						  v-model="queryParams.keywords"
						  style="width:320px"
						  placeholder="输入客户端名称或地址进行搜索"
						  class="input-with-select"
						   @keyup.enter="handleQuery"
						>
						  <template #append>
							<el-button icon="search"  @click="handleQuery" />
						  </template>
						</el-input>
					</div>
				</div>
				<div>
					<el-table
					  ref="dataTableRef"
					  v-loading="loading"
					  :data="mqttList"
					  highlight-current-row
					  border
					  height="calc(100vh - 260px)"
					  @selection-change="handleSelectionChange"
					>
					  <el-table-column type="selection" width="55" align="center" />
					  <el-table-column label="客户端名称" prop="name" align="left" min-width="120" />
					  <el-table-column label="服务器地址" prop="host" align="left" min-width="180" show-overflow-tooltip />
					  <el-table-column label="客户端类型" prop="type" align="center" width="120">
					    <template #default="scope">
					      <el-tag :type="getClientTypeTag(scope.row.type)">
					        {{ getClientTypeLabel(scope.row.type) }}
					      </el-tag>
					    </template>
					  </el-table-column>

					  <el-table-column label="默认运行" align="center" prop="defaultRunning" width="100">
					    <template #default="scope">
					      <el-tag :type="scope.row.defaultRunning == '1' ? 'success' : 'info'">
					        {{ scope.row.defaultRunning == '1' ? "是" : "否" }}
					      </el-tag>
					    </template>
					  </el-table-column>
					  
						<el-table-column label="运行状态" align="center" prop="isRunning" width="100">
							<template #default="scope">
							  <el-tag :type="scope.row.isRunning == '1' ? 'success' : 'danger'">
								{{ scope.row.isRunning == '1' ? "运行中" : "停止" }}
							  </el-tag>
							</template>
						</el-table-column>
						<el-table-column label="最近连接时间" prop="lastTime" align="left" width="180" />
						<el-table-column label="创建时间" prop="createTime" align="left" width="180" />
					  <el-table-column fixed="right" label="操作" width="320">
					    <template #default="scope">
					      <el-button
					        type="primary"
					        link
					        icon="Edit"
					        @click="editMqttDrawerRef.openDialog(scope.row,'edit')"
					      >
					        编辑
					      </el-button>
						  
						  <el-button
						    :type="scope.row.isRunning == '1' ? 'danger' : 'success'"
						    size="small"
						    link
						    :icon="scope.row.isRunning == '1' ? 'SwitchButton' : 'VideoPlay'"
						    @click="handleUpdateStatus(scope.row)"
						  >
						    {{ scope.row.isRunning == '1' ? '停止' : '启动' }}
						  </el-button>
						  
					      <el-button
					        type="danger"
					        link
					        icon="Delete"
					        @click="handleDelete(scope.row.id)"
					      >
					        删除
					      </el-button>
					    </template>
					  </el-table-column>
					</el-table>
					
					<div style="display: flex;justify-content: flex-end;align-items: center">
						<pagination
						  v-model:total="total"
						  v-model:page="queryParams.cur"
						  v-model:limit="queryParams.limit"
						  @pagination="handleQuery"
						/>
					</div>
				</div>
			</div>
		</div>
	</div>  
	<EditMqttDrawer  ref="editMqttDrawerRef" @close-dialog="handleQuery"></EditMqttDrawer>
  </div>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted } from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import EditMqttDrawer from "./components/EditMqttDrawer.vue";
	import MqttAPI, { MqttClientForm } from "@/api/biz/LDMPMqttClient";

	defineOptions({
	  name: "Mqtt",
	  inheritAttrs: false,
	});

	const datasourceFormRef = ref(ElForm);
	const loading = ref(false);
	const ids = ref<string[]>([]);
	const total = ref(0);
	const editMqttDrawerRef = ref();
	const mqttList = ref<MqttClientForm[]>([]);

	const queryParams = reactive({
	  cur: 1,
	  limit: 10,
	  keywords: ''
	});

	// 获取客户端类型标签样式
	const getClientTypeTag = (type: any) => {
	  const map: Record<any, any> = {
		'0': 'info',    // 消费者
		'1': 'warning', // 生产者
		'2': 'success'  // 消费者&生产者
	  };
	  return map[type] || 'info';
	};

	// 获取客户端类型标签文本
	const getClientTypeLabel = (type: string) => {
	  const map: Record<string, string> = {
		'0': '消费者',
		'1': '生产者',
		'2': '消费者&生产者'
	  };
	  return map[type] || '未知';
	};

	// 查询
	function handleQuery() {
	  loading.value = true;
	  MqttAPI.pages(queryParams)
		.then((response:any) => {
		  mqttList.value = response.list;
		  total.value = response.totalRow;
		})
		.finally(() => {
		  loading.value = false;
		});
	}

	// 重置查询
	function handleResetQuery() {
	  queryParams.cur = 1;
	  handleQuery();
	}

	// 行复选框选中
	function handleSelectionChange(selection: any) {
	  ids.value = selection.map((item: any) => item.id);
	}


	const handleUpdateStatus=(row?: any)=>{
		if(row.isRunning == '1'){
			handleStop(row);
		}else{
			handleStart(row);
		}
	}

	function handleStart(row?: any) {
	  ElMessageBox.confirm("确认启动客户端"+row.name+"?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	  }).then(
		() => {
		  loading.value = true;
		  MqttAPI.startClient(row.id)
			.then(() => {
			  ElMessage.success("启动成功");
			  handleQuery();
			})
			.finally(() => (loading.value = false));
		},
		() => {
		  ElMessage.info("已取消");
		}
	  );
	}

	function handleStop(row?: any) {
	  ElMessageBox.confirm("确认停止客户端"+row.name+"?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	  }).then(
		() => {
		  loading.value = true;
		  MqttAPI.stopClient(row.id)
			.then(() => {
			  ElMessage.success("停止成功");
			  handleQuery();
			})
			.finally(() => (loading.value = false));
		},
		() => {
		  ElMessage.info("已取消");
		}
	  );
	}

	// 删除客户端
	function handleDelete(id?: string) {
	  const deleteIds = id ? [id] : ids.value;
	  if (!deleteIds.length) {
		ElMessage.warning("请选择要删除的客户端");
		return;
	  }

	  ElMessageBox.confirm("确认删除选中的客户端?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	  }).then(
		() => {
		  loading.value = true;
		  MqttAPI.delete(deleteIds)
			.then(() => {
			  ElMessage.success("删除成功");
			  handleQuery();
			})
			.finally(() => (loading.value = false));
		},
		() => {
		  ElMessage.info("已取消删除");
		}
	  );
	}

	onMounted(() => {
	  handleQuery();
	});
</script>

<style lang="scss" scoped>
	.left{
		width: 320px;
		margin-right: 10px;
	}
	.right{
		width: calc(100% - 220px);
	}
	.table-tool-bar{
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 5px;
	}
	:deep(.el-table th.el-table__cell) {
		/* background-color: #fafafa; */
		background-color: #eee;
		background-image: url();
		background-image: -webkit-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -moz-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -o-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
		font-size: 12px;
	}
</style>
